<?php
class MissionModel extends Model {
	public $list;
	public $listmap;
	//特殊表格自动加分的方法
	public function daily(){
		import("@.ORG.Integrals.Integral");
		$class=new Integral(session(C('USER_AUTH_KEY')));
		$scheduleDB=M('Schedule');
		$eventDB=M('Event');
		$missionData=$this->where(['site_id'=>__SITEID__,'state'=>3,'particular'=>2])->select();//['gt',0]  特殊表格为 2 员工入职表
		
		foreach($missionData as $v){
			$eventData=$eventDB->where(['mission_id'=>$v['id'],'site_id'=>__SITEID__])->select();
			foreach($eventData as $vo){
				$result=$class->addIntegral($vo,$v);
				if($result){
					$ret[]=$result;	
				}else{
					//存储错误信息
					$str=' event_id='.$vo['id'].' , mission_id='.$v['id'].', \r\n function=daily, extend_function=addIntegral ,\r\n '.$result;
					writelog($str);	
				}
			}
		}
		return count($ret); 
	}
	//创建一条记录
	public function addMission($info){
		$ret=$this->where(['task_hide_id'=>$info['id']])->find();
		if($ret==false){
			$memberDB=M('Member');
			$integraltype = M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();
			foreach($integraltype as $k => $v){
				$formula[] = "proposer:".$v['typename']."=".intval($_POST[$v['typename']]);
				$value[] = '申请'.$v['remark'].'：'.intval($_POST[$v['typename']]);
			}
			$data['formula'] = implode(',', $formula);
			$data['formtemplate'] = $info['remark'];
			$data['formtemplateText'] = $info['remark'];
			//默认为设置表单为任务通知单
			$formInfo=M('Form')->where(['site_id'=>__SITEID__,'name'=>'任务通知单'])->field('id,formcategory_id')->find();
			$data['form_id'] = $formInfo['id'];
			$data['formcategory_id'] = $formInfo['formcategory_id'];
			$data['state']=1;
			$data['member_id'] = $info['member_id'];
			$data['reviewer_id'] = $info['creator_id'];
			$data['approvername']=$memberDB->where(['id'=>$info['creator_id']])->getField('name');
			$data['proposername']=$info['member_name'];
			$data['starttime']=$info['starttime'];
			$data['endtime']=$info['endtime'];
			$data['missionType'] = 1;
			$data['title'] = $info['member_name'].'的任务完成表';
			$data['record'] = build_order_no();
			$data['site_id'] = __SITEID__;
			$data['createtime'] = time();
			$data['detail'] = $info['remark'];
			$data['task_hide_id']=$info['id'];
			$info['endtime']=time();
			$info['detail']=$info['remark'];
			$data['integralret']=serialize([$info['member_id']=>['name'=>$info['member_name'],'integral'=>unserialize($info['integralNum'])]]);
			$data['object']=serialize($info);
			$ret = $this->add($data);
			//$ret=$missionDB->where(['id'=>$ret])->find();
		}	
		return $ret;
	}
	//列表
	public function _list($view,$map,$sort='sort',$pagesize=20){
		//计算总页数
		$count=$this->where($map)->count();
		//实例化分页类
		import ( 'ORG.Util.Page' );
		$p=new Page($count,$pagesize);
		$list = $this->where($map)->order($sort)->limit($p->firstRow.',
'.$p->listRows)->select();
        foreach($list as $k => $v){
			$list[$k]['progress'] = M('Schedule') -> where(array('mission_id' => $v['id'])) -> order('datatime desc') -> select();
		}
        $pages=$p->show();
		$view->assign('list',$list);
		$view->assign('pages',$pages);
	}
	//审批筛选返回where
	public function filter(){
		$this->listmap='1';
		/*if(isset($_REQUEST['type'])&&$_REQUEST['type']=='0'){//list
			$this->pagesize =15;
		}else{//index
			$this->pagesize = 8;//直接上级或者审批人查看
		}*/
		/*$InteType = M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();
		$InteTypeList = array();
		foreach($InteType as $k => $v){
			$InteTypeList[$v['typename']] = $v['remark'];
		}
		
		$this->InteTypeList = $InteTypeList;*/
		//state >= 0 and
		$this->listmap = " site_id = ". __SITEID__." and (approver_id = '".session(C('USER_AUTH_KEY'))."' or reviewer_id='".session(C('USER_AUTH_KEY'))."' or approver like '%,".session(C('USER_AUTH_KEY')).",%')";
		if(!empty($_REQUEST['keywords'])){
			$keywords=$_REQUEST['keywords'];
			$_GET['keywords']=urlencode($_REQUEST['keywords']);
			if(isset($_REQUEST['mymission'])){
				$this->listmap.=" and ( proposername like '%".$keywords."%' or title like '%".$keywords."%' ) ";
			}else{	
				$this->listmap.=" and ( proposername like '%".$keywords."%' or approvername like '%".$keywords."%' or title like '%{$keywords}%' ) ";
			}
			$this->keywords=$keywords;
		}
		if(isset($_REQUEST['formcategory_id'])){
			$id=$_REQUEST['formcategory_id'];
			$this->listmap.=' and formcategory_id = '.$id;
		}
		/*if($_REQUEST['pagesize']){
			$this->pagesize=$_REQUEST['pagesize'];
			$this->assign('pagesize',$this->pagesize);
		}*/
//		if($this->_param('id')){
//			$id=$this->_param('id');
//			$this->listmap.= ' and formcategory_id = '.$id;
//		}
        /*if(isset($_REQUEST['status'])&&$_REQUEST['status']!=99||$_REQUEST['status']=='0'){

            $this->listmap.=" and state = ".$_REQUEST['status'];
            //$this->status=$_REQUEST['status'];
        }*/
        if ($_REQUEST['starttime'] || $_REQUEST['endtime']) {
            $stime = strtotime($_REQUEST['starttime']);
            $etime = strtotime($_REQUEST['endtime']) + 24 * 3600;
            if ($_REQUEST['starttime']) {
                $this->listmap .= " and createtime >= '" . $stime . "'";
                //$this->starttime=date('Y-m-d H:i:s',$stime);
            }
            if ($_REQUEST['endtime']) {
                $this->listmap .= " and createtime <= '" . $etime . "'";
                //$this->endtime	=date('Y-m-d H:i:s',$etime);
            }
            if ($_REQUEST['starttime'] && $_REQUEST['endtime']) {
                $this->listmap .= " and createtime <= '" . $etime . "'";
                $this->listmap .= " and createtime >= '" . $stime . "'";
                //$this->starttime=date('Y-m-d H:i:s',$stime);
                //$this->endtime	=date('Y-m-d H:i:s',$etime);
            }
        }
		/*if(isset($_GET['state']) && intval($_GET['state']) >= 0){
			if($_GET['state'] != 'all'){
				$this->listmap .= " and state = '" . intval($_GET['state']) . "'";
			}
		}*/
		$category=D('formcategory')->select();//查找分类
		foreach($category as $key => $value){
			$map=$this->listmap;
			$map .= ' and formcategory_id = '.$value['id'];
			$category[$key]['count']=D('mission')->where($map)->count();
		}
		return $this->listmap;
		/*$this->assign('candy',$category);//分类渲染
		$this->listorder='state';

		
		if($_REQUEST['sorttype']){
			$sorttype=$_REQUEST['sorttype'];
			$sorttype=explode('_',$sorttype);
			$typeid=$sorttype[0];//排序字段
			$typeval=$sorttype[1];//排序方式 1正2倒
		}
		if($typeid != ''){
			switch($typeid){
				case 4 :
					$sortby="memberstring";break;
				case 5 :
					$sortby='createtime';break;
			}
			switch($typeval){
				case 1 :$sort='asc';break;
				case 2 :$sort='desc';break;
			}
			$this->listorder=$sortby.' '.$sort;
		}*/
	}
	//通过一个工作ID，递龟得出自己属于这条线的自己的数组
	public function getParentMission($id,$member_id,$arr){
		$data=$this->where('id='.$id)->Field('id,member_id,pid')->find();
		if($data){
			if($data['member_id']==$member_id){
				$arr[]=$id;	
			}
			return $this->getParentMission($data['pid'],$member_id,$arr);
		}else{
			return $arr;
		}
	}
	//通过一个工作ID，递龟获取所有的父工作的负责人
	public function getParentMember($id,$list=''){
		$data=$this->where('id='.$id)->Field('id,member_id,pid')->find();
		if($data){
			$list.=','.$data['member_id'];
			return $this->getParentMember($data['pid'],$list);
		}else{
			return $list;
		}
	}
	//查看一个工单的详情
	public function _getOne($view, $id = 0){
		$data['progress'] = M('Schedule') -> where(array('mission_id' => $id)) -> order('datatime desc') -> select();
		$data['info'] = $this->where(array('id' => $id)) -> find();
		$data['res'] = $this -> createOne($view, $data['info']['id']);
		return $data;
	}
	public function findOne($map){
		return $this->where($map)->find();	
	}
	//还原一个表单
	public function createOne($view,$id){
		$data = $this -> where(array('id' => $id)) -> find();
		
		$object = unserialize($data['object']);
		
		$view -> assign($object);
		$Field = M('field');
		$fields = $Field ->where(array('form_id' => $data['form_id'])) -> select();
		
		foreach($fields as $v){
			//将字段名对应到表单中
			if($v['f_type']==2){//如果该表单类型为2 即文本域 那么就改变渲染到页面的值
				$view->assign('field_'.$i,'<a href="'.substr($view->get($v['f_name']),1,strlen($view->get($v['f_name']))).'">下载查阅</a>');
				continue;
			}
			$view->assign('field_'.$v['id'],$view->get($v['f_name']));
			
		}
		
		//渲染表单数据到页面
		$form = M('Form') -> where(array('id' => $data['form_id'])) -> find();
		return $view->fetch('',$form['template']);
	}
	
	
	//分发审批
	//$copy 是否复制副本分发
	//$member_id 分发给谁
	public function sendTo($member_id, $copy = 0){
		$mission = $this->find();
		$mdb = M('Member');
		if($mission){
			$memberInfo = session('memberInfo');
			if($mission['member_id'] == $memberInfo['id']){
				//会员是否存在
				$member = M('Member') -> where(array('site_id' => __SITEID__, 'id' => $member_id)) -> find();
				if($member){
					if($copy == 0){
						$name = $mdb -> where(array('id' => $member_id)) -> getField('name');
						//审核人
						
						$ret = $this -> where(array('id' => $mission['id'])) -> save(array('member_id' => $member_id, 'proposername' => $name));
						$this->setTaskMembers($this -> where(array('id' => $mission['id'])) -> find());
					}else{
						$mission['member_id'] = $member_id;
						$mission['proposername'] = $mdb -> where(array('id' => $member_id)) -> getField('name');
						unset($mission['id']);
						$ret = $this-> add($mission);
						$this->setTaskMembers($mission);
					}
					if($ret !== false){
						return true;
					}else{
						return false;
					}
				}else{
					return false;
				}
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	
	public function setTaskMembers($mission){
		$taskdb = M('Task');
		$list = $this->where(array('task_id' => $mission['task_id'])) -> Field('member_id') -> select();
		$members = array();
		foreach($list as $k => $v){
			if(!in_array($v['member_id'], $members)){
				$members[] = $v['member_id'];
			}
		}
		$taskdb -> where(array('id' => $mission['task_id'])) -> save(array('members' => ','.implode(',', $members).','));
	}
	
	//计算积分入库
	public function createevent($view){
		$mission = $this->find();
		$memberInfo = session('memberInfo');
		$memberdb = M('Member');
		$integral_typedb = M('Integral_type');
		$Integral_numberdb = M('Integral_number');
		$Integral_logdb = M('Integral_log');
		$MP = M('Member_position');
	    //计算这个审批的平均分
		//查找所有的审批记录
		if($Integral_logdb -> where(array('mission_id' => $mission['id'])) -> find()){
			return false;
		}
		$integralconfig = unserialize($memberInfo['integralconfig']);
		$scheduledb = M('Schedule');
		$schedule = $scheduledb -> where(array('mission_id' => $mission['id'])) -> select();
		$integral = array();
		$flag = true;
		foreach($schedule as $k => $v){
			$integrals = unserialize($v['integrals']);
			foreach($integrals as $key => $val){
				$integral[$val['type'].'_'.$val['member_id']] += $val['num'];
				//检查当前审批人的积分权限
				if($integralconfig[$val['type']][2] < abs($val['num']) && $mission['task_id'] == 0 && $memberInfo['pid'] > 0){
					$flag = false;
					$this->error = '当前分配的积分超出了用户的积分权限！';
					return false;
				}
			}
		}
		foreach($integral as $k => $v){
			$keydata = explode('_', $k);
			$num = $v/count($schedule);
			//初始化积分账户
			import("@.ORG.Integrals.".$keydata[0]);
			$integralobj = new $keydata[0]($keydata[1]);
			if($num == 0){
				continue;
			}
			
			$memberpositionid = $memberdb -> where(array('site_id' => __SITEID__,'id' => intval($keydata[1]))) -> getField('memberpositionid');
			
			$event['member_id'] = intval($keydata[1]);
			$event['site_id'] = __SITEID__;
			$event['remark'] = $mission['formtemplateText'];
			$event['integralnumber'] = intval($num);
			$integral_type = $integral_typedb -> where(array('typename' => $keydata[0], 'site_id' => __SITEID__)) -> find();
			//dump($integral_type);
			$event['integraltypeid'] = $integral_type['id'];
			$event['integraltypename'] = $integral_type['remark'];
			$memberIo = $memberdb -> where(array('id' => $event['member_id'])) -> find();
			$event['membername'] = $memberIo['name'];
			$event['datetime'] = time();
			$event['form_id'] = $mission['form_id'];
			$event['formname'] = $mission['title'];
			$event['approver'] = $mission['approver'];
			$event['approvername'] = $mission['approvername'];
			$event['task_id'] = $mission['task_id'];
			$event['mission_id'] = $mission['id'];
			$event['memberpositionid'] = $memberpositionid;
			$eventid = M('Event') -> add($event);
			//写入积分日志
			$integrallog['type_id'] = $event['integraltypeid'];
			$integrallog['remark'] = $event['remark'];
			$integrallog['changenum'] = $event['integralnumber'];
			$integrallog['member_id'] = $event['member_id'];
			$integrallog['site_id'] = __SITEID__;
			$integrallog['memberpositionid'] = $memberpositionid;
			
			$integrallog['attrkey'] = $memberIo['attrkey'];
			$integrallog['memberpositionname'] = $memberIo['memberpositionname'];
			$integrallog['membername'] = $event['membername'];
			$integrallog['integralname'] = $integral_type['remark'];
			$integrallog['approvername'] = $mission['approvername'];
			
			
			//dump($integrallog);
			
			//改变用户积分总数
			$Integral_numberdb -> where(array('site_id' => __SITEID__, 'member_id' => $event['member_id'], 'type_id' => $integrallog['type_id'])) -> setInc('number', $integrallog['changenum']);
			
			
			//echo $Integral_numberdb -> getLastSql();
			
			$integrallog['totalnum'] = (float)$Integral_numberdb -> where(array('type_id' => $integrallog['type_id'], 'site_id' => __SITEID__, 'member_id' => $event['member_id'])) -> getField('number');
			$integrallog['event_id'] = $eventid;
			$integrallog['form_id'] = $mission['form_id'];
			$integrallog['mission_id'] = $mission['id'];
			
			
			$times = array_pop($schedule);
			$integrallog['time'] = $times['datatime'];
			
			
			$integrallog['attrkey']=$mission['attrkey'];
			
			$integrallog['rule_id']=intval($mission['rule_topid']);
			$integrallog['giver_id'] = $memberInfo['id'];
			$integrallog['rewarder_id'] = $memberInfo['id'];
			$integrallog['formcategory_id']=D('Form')->where('id ='.$mission['form_id'])->getField('formcategory_id');
			$integrallog['formcategoryname'] = M('Formcategory') -> where(array('id' => $integrallog['formcategory_id'])) -> getField('name');
			//dump($mission);exit;
//			$Integral_logdb -> add($integrallog);
			$integrallog['integrallogid'] = $Integral_logdb -> add($integrallog);
			
			D('Integralranking') -> getDataFromLog($integrallog);
		}
		 

		if($mission['task_id'] > 0){
			D('Task') -> where(array('id' => $mission['task_id'], 'site_id' => __SITEID__)) -> updateprogress();
		}
		
		return;
		
		
		
		
		
//		$memberdb = M('Member');
//		$integral_typedb = M('Integral_type');
//		$Integral_numberdb = M('Integral_number');
//		$Integral_logdb = M('Integral_log');
//
//		if($Integral_logdb -> where(array('site_id' => __SITEID__, 'mission_id' => $mission['id'])) -> find()){
//			return false;
//		}
//
//		$formdata = unserialize($mission['object']);
//		$memberInfo = session('memberInfo');
//		//积分规则多选时，转换数量
//		if(is_array($formdata['rule'])){
//			$num = 0;
//			for($i = 0; $i < count($formdata['rule']); $i ++){
//				$num += $formdata['rule'][$i];
//			}
//			$formdata['rule'] = $num;
//		}
//		$view -> assign($formdata);
//		$formula = trimall($mission['formula']);
//		if($formula == ''){
//			$this->error = '积分计算公式为空，无法计算分数！';
//
//			return false;
//		}
//		$formula = explode(',', trimall($mission['formula']));
//		foreach($formula as $k => $v){
//			//用户和积分类型和公式
//			$memberandintegraltypeandformula = explode('=', $v);
//			$memberandintegraltype = explode(':', $memberandintegraltypeandformula[0]);
//
//
//			if($memberandintegraltype[0] == 'approver' || $memberandintegraltype[0] == 'approver_id' || $memberandintegraltype[0] == 'proposer'){
//				if($memberandintegraltype[0] != '' && $memberandintegraltype[0] == 'approver'){
//					$memberids = explode(',', trim($mission['approver'], ','));
//				}elseif($memberandintegraltype[0] == 'approver_id'){
//					$memberids = array($mission['member_id']);
//				}else{
//					$pid = M('Member') -> where(array('id' => $mission['member_id'])) -> getField('id');
//					if($pid > 0){
//						$memberids = array($pid);
//					}
//				}
//
//
//			}else{
//				$memberids = $view -> get($memberandintegraltype[0]);
//			}
//			//
//			foreach($memberids as $val){
//				//计算积分
//
//
//				$memberandintegraltypeandformula[1] = 'intval('.$memberandintegraltypeandformula[1].')';
//				$intefetchret = $view -> fetch('',$memberandintegraltypeandformula[1]);
/*				$ret = $view -> fetch('','<?php echo round('.$intefetchret.', 0);?>'); */
//
//
//
//
//				if(intval($val) > 0 && intval($ret) != 0){
//					$event['member_id'] = intval($val);
//					$event['site_id'] = __SITEID__;
//					$event['remark'] = $val.':'.$memberandintegraltype[1].'积分变动'.$ret;
//					$event['integralnumber'] = intval($ret);
//
//					$integral_type = $integral_typedb -> where(array('typename' => $memberandintegraltype[1])) -> find();
//
//					$event['integraltypeid'] = $integral_type['id'];
//					$event['integraltypename'] = $integral_type['remark'];
//
//					$event['membername'] = $memberdb -> where(array('id' => $event['member_id'])) -> getField('name');
//					$event['datetime'] = time();
//					$event['form_id'] = $mission['form_id'];
//					$event['formname'] = intval($val);
//					$event['approver'] = $mission['approver'];
//					$event['approvername'] = $mission['approvername'];
//					$event['task_id'] = $mission['task_id'];
//					$event['mission_id'] = $mission['id'];
//
//					$eventid = M('Event') -> add($event);
//
//					//写入积分日志
//					$integrallog['type_id'] = $event['integraltypeid'];
//					$integrallog['remark'] = $event['remark'];
//					$integrallog['changenum'] = $event['integralnumber'];
//					$integrallog['member_id'] = $event['member_id'];
//					$integrallog['site_id'] = __SITEID__;
//
//					//改变用户积分总数
//					$Integral_numberdb -> where(array('site_id' => __SITEID__, 'member_id' => $event['member_id'], 'type_id' => $integrallog['type_id'])) -> setInc('number', $integrallog['changenum']);
//					$integrallog['totalnum'] = (float)$Integral_numberdb -> where(array('type_id' => $integrallog['type_id'], 'site_id' => __SITEID__, 'member_id' => $event['member_id'])) -> getField('number');
//					$integrallog['event_id'] = $eventid;
//					$integrallog['form_id'] = $mission['form_id'];
//					$integrallog['mission_id'] = $mission['id'];
//					$integrallog['time'] = $event['datetime'];
//					$integrallog['giver_id'] = $memberInfo['id'];
//					$integrallog['rewarder_id'] = $memberInfo['id'];
//					$integrallog['integrallogid'] = $Integral_logdb -> add($integrallog);
//
//					D('Integralranking') -> getDataFromLog($integrallog);
//				}
//
//
//			}
//
//
//		}
//
//
//		if($mission['task_id'] > 0){
//			D('Task') -> where(array('id' => $mission['task_id'], 'site_id' => __SITEID__)) -> updateprogress();
//		}
		 
		
		
	}
	//计算积分入库
	public function deleteevent($view){
		$mission = $this->find();
        //dump($mission);
		$memberdb = M('Member');
		$integral_typedb = M('Integral_type');
		$Integral_numberdb = M('Integral_number');
		$Integral_logdb = M('Integral_log');
		$formdata = unserialize($mission['object']);
		$memberInfo = session('memberInfo');
		
		
		//查找所有积分记录
		$integral_log = $Integral_logdb -> where(array('site_id' => __SITEID__, 'mission_id' => $mission['id'])) -> select();
		
		//扣除积分
		foreach($integral_log as $v){

			$intlogid=$Integral_logdb -> where(array('site_id' => __SITEID__, 'member_id' => intval($v['member_id']), 'type_id' => $v['type_id'],'mission_id'=>$mission['id'])) ->getfield('id');
			$re=D('Integral_log')->changeTotalnum($intlogid,$v['member_id'],$v['num'],1);
			if($re){
				var_dump($re);exit;
			}else{

				var_dump($re);exit;
			}
			$Integral_numberdb -> where(array('site_id' => __SITEID__, 'member_id' => intval($v['member_id']), 'type_id' => $v['type_id'])) -> setDec('number', intval($v['num']));
			
			$deleteret = $Integral_logdb -> where(array('site_id' => __SITEID__, 'member_id' => intval($v['member_id']), 'type_id' => $v['type_id'],'mission_id'=>$mission['id'])) -> delete();

		}

		
		D('Integralranking') -> where(array('site_id' => __SITEID__, 'mission_id' => $mission['id'])) -> delete();
		
		if($mission['task_id'] > 0){
			D('Task') -> where(array('id' => $mission['task_id'], 'site_id' => __SITEID__)) -> updateprogress();
		}
		 
		 
		return;
		 
		 
		 
		 
		//积分规则多选时，转换数量
		if(is_array($formdata['rule'])){
			$num = 0;
			for($i = 0; $i < count($formdata['rule']); $i ++){
				$num += $formdata['rule'][$i];
			}
			$formdata['rule'] = $num;
		}
		$view -> assign($formdata);
		//dump($mission);
		$formula = trimall($mission['formula']);
		if($formula == ''){
			return false;
		}
		$formula = explode(',', trimall($mission['formula']));
		foreach($formula as $k => $v){
			//用户和积分类型和公式
			$memberandintegraltypeandformula = explode('=', $v);
			$memberandintegraltype = explode(':', $memberandintegraltypeandformula[0]);
			
			
			if($memberandintegraltype[0] == 'approver' || $memberandintegraltype[0] == 'approver_id' || $memberandintegraltype[0] == 'proposer'){
				if($memberandintegraltype[0] != '' && $memberandintegraltype[0] == 'approver'){
					$memberids = explode(',', trim($mission['approver'], ','));
				}elseif($memberandintegraltype[0] == 'approver_id'){
					$memberids = array($mission['member_id']);
				}else{
					$pid = M('Member') -> where(array('id' => $mission['member_id'])) -> getField('id');
					if($pid > 0){
						$memberids = array($pid);
					}
				}
				
				
			}else{
				$memberids = $view -> get($memberandintegraltype[0]);
			}
			
			foreach($memberids as $val){
				//计算积分
				//$memberandintegraltypeandformula[1] = 'intval('.$memberandintegraltypeandformula[1].')';
			    $intefetchret = $view -> fetch('',$memberandintegraltypeandformula[1]);
			    $ret = $view -> fetch('','<?php echo round('.intval($intefetchret).', 0);?>');
			    
				
				if(intval($val) > 0 && intval($ret) != 0){
					
					$integral_type = $integral_typedb -> where(array('typename' => $memberandintegraltype[1])) -> find();
					
					//改变用户积分总数
					
					
					$deleteret = $Integral_logdb -> where(array('site_id' => __SITEID__, 'member_id' => intval($val), 'type_id' => $integral_type['id'],'mission_id'=>$mission['id'])) -> delete();
					if($deleteret > 0){
						$Integral_numberdb -> where(array('site_id' => __SITEID__, 'member_id' => intval($val), 'type_id' => $integral_type['id'])) -> setDec('number', intval($ret));
					}
					//D('Integralranking') -> getDataFromLog($integrallog);
				}
				
				 
			}
			
			
		}
		
		D('Integralranking') -> where(array('site_id' => __SITEID__, 'mission_id' => $mission['id'])) -> delete();
		
		if($mission['task_id'] > 0){
			D('Task') -> where(array('id' => $mission['task_id'], 'site_id' => __SITEID__)) -> updateprogress();
		}
		 
		
		
	}
	public function geteventIntegral($view, $integral = array()){
		//用户自定积分数量，是一个多维组
		
		$mission = $this->find();
		$memberdb = M('Member');
		$integral_typedb = M('Integral_type');
		$Integral_numberdb = M('Integral_number');
		$Integral_ruledb=D('Integral_rule');
		$Integral_logdb = M('Integral_log');
		$formdata = unserialize($mission['object']);
		$memberInfo = session('memberInfo');
		
		$integraltypel = $integral_typedb -> where(array('site_id' => __SITEID__)) -> select();
		foreach($integraltypel as $k => $v){
			$formdata[$v['typename']] = 0;
		}
		//dump();
		$formdata['rule']=0;
		
		
		if(count($integral) == 0){
			//积分规则多选时，转换数量
			if(is_array($formdata['rule'])){
				$num = 0;
				for($i = 0; $i < count($formdata['rule']); $i ++){
					$num += $formdata['rule'][$i];
				}
				$formdata['rule'] = $num;
			}
		}else{
			foreach($integral as $v){
				if(!isset($v['id'])){
					foreach($v as $ikey => $inte){
						//把积分算出来
						if(isset($formdata[$ikey])){
							$formdata[$ikey] += $inte;
						}else{
							$formdata[$ikey] = $inte;
						}
					}
				}
			}
		}
		
		
		
	//	dump($formdata);
		
		
		$view -> assign($formdata);
		//dump($mission);
		$formula = trimall($mission['formula']);
		if($formula!=''){
			$formula = explode(',', trimall($mission['formula']));
			$r = array();
			foreach($formula as $k => $v){
				//用户和积分类型和公式
				$memberandintegraltypeandformula = explode('=', $v);
				$memberandintegraltype = explode(':', $memberandintegraltypeandformula[0]);
				//$memberandintegraltypeandformula[1] = 'intval('.$memberandintegraltypeandformula[1].')';
				if($memberandintegraltypeandformula[1] == ''){
					$memberandintegraltypeandformula[1] = '{$rule}';
				}else{
					$memberandintegraltypeandformula[1]=str_replace('{$rule}','{$'.$memberandintegraltype[1].'}',$memberandintegraltypeandformula[1]);
				}
				
				//dump($memberandintegraltypeandformula[1]);
				
				$intefetchret = $view -> fetch('',$memberandintegraltypeandformula[1]);
				
					
				if($memberandintegraltype[0] == 'proposer'){
					$memberkey = $mission['member_id'];
					$membername = $mission['proposername'];
				}
				$r[$memberkey]['name'] = $membername;
				//$r[$memberkey]['integralname']
				
				$r[$memberkey]['integral'][$memberandintegraltype[1]] += $view -> fetch('','<?php echo round('.$intefetchret.', 0);?>');
			}
		}

		//如果有规则源的话，替换算好的分数
		if(!empty($formdata['integral'])&&$formula==''){
			$r[$mission['member_id']]['name']=$mission['proposername'];
			$r[$mission['member_id']]['integral']=$Integral_ruledb->getIntegral($formdata['integral']);
			unset($r['']);
		}
		return $r;
	}

	//当前审批分配积分，分配给谁

	public function geteventIntegralArray($view){
		$mission = $this->find();
        $r = unserialize($mission['integralret']);
		
		return $r;
	}
	public function selectall($map,$field,$group='',$order=''){
		//Neah Lawrence 2017/1/12
		$r=$this->where($map)->field($field)->group($group)->order($order)->select();
		return $r;
	}
	public function findOne2($map,$field,$group='',$order=''){
		$r=D('Mission')->where($map)->group($group)->order($order)->field($field)->find();
		return $r;
	}
	
	//通过审批
	public function pass($data, $view){
			$db = M('Schedule');
			$ticketDB=D('Ticket');
			$mission = $this -> where(array('id' => $data['mission_id'])) -> find();

			$memberInfo = session('memberInfo');
			if($mission['approver_id'] != $memberInfo['id'] && $mission['reviewer_id'] != $memberInfo['id'] && strpos($mission['approver'], ','.$memberInfo['id'].',') === false&&(!empty($mission['approver_id'])&&!empty($mission['reviewer_id']))){
				$this->error = '您对当前工作无审批权限！';
				return false;
			}
			//判断如果任务没有表格ID，则返回状态2
			if(!$mission['formcategory_id']&&$data['status']){
				return ['status'=>2];
			}
			//找一条记录出来

			$map['mission_id'] = $data['mission_id'];
			$map['member_id'] = $memberInfo['id'];
			$info = $db -> where($map) -> find();
			$data['member_id'] = $memberInfo['id'];
			$data['datatime'] = isset($data['datatime'])?$data['datatime']:time();
			$data['membername'] = M('Member') -> where(array('id' => $memberInfo['id'])) -> getField('name');
			if(isset($data['send'])){
				$data['sendParent'] = 1;
			}
			
			$integrals = array();
			//$flag = true;
			$integralconfig = unserialize($memberInfo['integralconfig']);
			
			foreach($data['integralmember_id'] as $k => $v){
				$d['member_id'] = $v;
				$d['type'] = $data['integraltype'][$k];
				$d['num'] = $data['integralnum'][$k];
				$d['name'] = M('Member') -> where(array('id' => $v, '' => __SITEID__)) -> getField('name');
				$integrals[] = $d;
				if($integralconfig[$d['type']][2] < abs($d['num']) && $mission['task_id'] == 0){
					if((intval($data['send']) == 0 && $memberInfo['pid'] > 0)){
						//不递交上级，权限不够不能审核
						$this->error = '当前分配的积分超出了用户的积分权限！';
					    return false;
					}
				}
			}
			
			if($data['status'] > 0){
				$data['integrals'] = serialize($integrals);
				//删除奖票
				$data['ticketnum'] = intval($data['ticket']);
				
			}else{
				$data['integrals'] = '';
				$data['ticketnum'] = 0;
			}
			
			
			//更新奖票数量

			$ticket_ret=$ticketDB -> sendticket($memberInfo['id'], $mission['member_id'], $data['ticketnum'], array('info_id' => 0, 'mission_id' => $mission['id']));
			if(!$ticket_ret){
				//暂无对奖票错误的方法
//				dump('错误，请重试。');exit;
			}
			
			
			if($info){
				
				$ret = $db -> where($map) -> data($data) -> save();
				
			}else{
				$ret = $db -> data($data) -> add();
				
			}

			if($ret){
				
				
				//更新当前审批状态
				$mission = $this -> where(array('id' => $mission['id'])) -> find();
				
				//将审核人ID作为键，计算数组长度就可知多少个审核人
				$arr = array();
				$approvercount = 0;
				$approverarr = explode(',', $mission['approver']);
				
				if($mission['approver_id'] > 0){
					$arr[] = $mission['approver_id'];
				}
				if($mission['other_id'] > 0){
					$arr[] = $mission['other_id'];
				}
				if($mission['reviewer_id'] > 0){
					$arr[] = $mission['reviewer_id'];
				}
				

				foreach($approverarr as $appk => $appv){
					if(intval($appv) > 0 && !in_array(intval($appv),$arr)){
						$arr[] = intval($appv);
					}
				}
				
				$arr1 = array();
				foreach($arr as $k => $v){
					if(!in_array($v,$arr1)){
						$arr1[] = $v;
					}
				}

				
				//是否递交上级
				if(isset($data['send'])){
					
					
					
					if($memberInfo['pid'] > 0){
						$arr1[] = $memberInfo['pid'];
						$this -> where(array('id' => $map['mission_id'])) -> data(array('approver' => ','.implode(',', $arr1).',')) -> save();
						//递交上级之后的上级ID放入审批记录表中
						$db->where(['id'=>$ret])->data(['parent_id'=>$memberInfo['pid']])->save();
						
					}
				}
				
				if(count($arr1) > 0){
					$approvernamearr = M('Member') -> where(array('site_id' => __SITEID__, 'id' => array('in', implode(',', $arr1)))) -> getField('name', true);
					$this -> where(array('id' => $mission['id'])) -> data(array('approvername' => implode(',', $approvernamearr))) -> save();
				}
				
				$arr = $arr1;
				$approvercount=count($arr);
				$schedule = $db -> where(array( 'mission_id' => $mission['id'])) -> select();
				if(count($schedule) == 0){
					//没有审批记录
					$sdata['state'] = 1;
				}else{
					$passcount = $turnedcount = 0;
					foreach($schedule as $k => $v){
					    if($v['status'] == 1){
							$passcount ++;
						}else{
							$turnedcount ++;
						}
				    }
					if($passcount >= $approvercount){
						//通过
						$sdata['state'] = 3;
						//改变任务的状态也为3
						if($mission['task_id']){
							$task=new Task();
							$task->changeStatus(3,$mission['task_id']);	
						}
						//如果为负责人任务，改状态为3，并加入task_id
						if($mission['task_hide_id']){
							//$this->where(['id'=>$mission['id']])->setField('task_id',$mission['task_hide_id']);
						}
					}
					if($passcount < $approvercount && $turnedcount == 0){
						//审批中
						$sdata['state'] = 2;
					}
					if($turnedcount > 0){
						//驳回
						$sdata['state'] = 0;
					}
				}
				//更新状态 
				$ret = $this -> data($sdata) -> where(array('id' => $mission['id'])) -> save();
				if($ret !== false && $sdata['state'] == 3){
					if($mission['particular']!=0&&$mission['particular']!=2){
						$missionData=$mission;
						$missionData['mission_id']=$mission['id'];
						unset($missionData['id']);
						D('Attendence')->data($missionData)->add();
					}
					//通过审批,更新状态成功，在这里这样计算分数
					$createret = $this -> where(array('id' => $mission['id'])) -> createevent($view);
					if($createret === false){
						return false;
					}	
				}
				if($ret !== false && $sdata['state'] == 0){
					//不通过审批,更新状态成功，在这里这样计算分数
					$this -> where(array('id' => $mission['id'])) -> deleteevent($view);
				}
				$return['state'] = $sdata['state'];
				$return['status'] = $ret !== false?1:0;
				$return['info'] = $ret !== false ?'操作成功':'操作失败，请重试。';
				return $return;
			}else{
				return false;
			}
			return true;
		
	}
	//限定条数的list
	public function _limit($view,$map,$order='id desc',$limit){
		$list = $this->where($map)->order($order)->limit($limit)->select();
		$view->assign('list',$list);
	}
	
}
